package com.chenchao.javageneric;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/13 15:18
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.javageneric.TreeSetTest.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * TreeSet不重复无序（指定的是不按照你添加的顺序）
 * 对元素进行排序
 * 添加到TreeSet必须实现Comparable
 */
public class TreeSetTest {
    public static void main(String[] args) {
        //test();
        //treeObject();
        comprepatorTest();
    }


    public static void test(){
        TreeSet<Integer> integers = new TreeSet<>();
        integers.add(1);
        integers.add(9);
        integers.add(10);
        integers.add(2);
        integers.add(5);
        System.out.println(integers);
        //前一个相同再比后一个
        TreeSet<String> s = new TreeSet<>();
        s.add("Dd");
        s.add("Ee");
        s.add("ED");
        s.add("G");
        System.out.println(s);
        //按照unicode编码排序
        TreeSet<String> s2 = new TreeSet<>();
        //String中实现了ComparbleTo
        s2.add("底");
        s2.add("放到");
        s2.add("放");
        s2.add("地的");
        System.out.println(s2);
    }

    /**
     * 自定义对象的二叉树集添加
     */
    public static void treeObject(){
        TreeSet<P> ps = new TreeSet<>();
        ps.add(new P("li",12));
        ps.add(new P("fds",13));
        ps.add(new P("dfs",121));
        ps.add(new P("li",15));
        boolean li = ps.add(new P("li", 12));
        System.out.println(li);
        System.out.println(ps);
        //先比较年龄，再比较name如果完全一样，
        // compareTo返回值为0，不添加
    }

    /**
     * 比较器对象测试
     */
    public static void comprepatorTest(){
        String a0="ooo";
        String a1="oo";
        String a2="oa";
        TreeSet<String> strings = new TreeSet<>(new StringCompartor());
        //创建二叉树集合时添加指定的对象比较器,
        //添加时会调用compare()方法进行比较
        strings.add(a0);
        strings.add(a1);
        strings.add(a2);
        System.out.println(strings);
    }
}
class StringCompartor implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {
        System.out.println("我被执行了");
        return o1.length()-o2.length()==0?o1.compareTo(o2):o1.length()-o2.length();
    }
    public int compare(Integer o1, Integer o2) {
        System.out.println("我被执行了");
        return 0;
    }
}
class P implements Comparable<P>{
    public String name;
    public int age;

    public P() {
    }

    public P(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(P o) {
        return o.age==this.age?
                o.name.compareTo(this.name):this.age-o.age;
    }

    @Override
    public String toString() {
        return "P{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

